<html>
<head>
<meta charset="UTF-8">
<title>Chat</title>
<script src="https://cdn.bootcss.com/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js"></script>
<script src="https://cdn.bootcss.com/recorderjs/0.1.0/recorder.js"></script>
<script>
   	var wsurl = (location.protocol.toString().startsWith("https") ? "wss://" : "ws://") + location.host + "/ws/chat";
    var socket = new ReconnectingWebSocket(wsurl);
    socket.onmessage = function (event) {
        var chat = document.getElementById('chat');
        chat.innerHTML = chat.innerHTML + event.data + "<br />";
        chat.scrollTop = chat.scrollHeight;
    };

    function send(message) {
        socket.send(message);
    }
    
    function onPaste(){
    	var event = window.event || arguments.callee.arguments[0];
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var index in items) {
            var item = items[index];
            if (item.type && item.type.match(/image.*/)) {
                var file = item.getAsFile();                        
                getBase64(file, function(base64){
                	send("<img src='"+base64+"'/>");
                })
            }
        }
    }
    
    function onSelect(){
    	var event = window.event || arguments.callee.arguments[0];
    	var files = event.target.files;
    	for(var index in files){
    		var file = files[index];
            if (file.type && file.type.match(/image.*/)) {
                getBase64(file, function(base64){
                	send("<img src='"+base64+"'/>");
                })
            }    		
    	}
    }
    //callback(base64)
    function getBase64(file, callback){
        var reader = new FileReader();
        reader.onload = function(event) {                            
            var base64 = event.target.result;
            callback(base64);
        };
        reader.readAsDataURL(file);    	
    }
    
    var navigator = window.navigator;
    var Context = window.AudioContext || window.webkitAudioContext;
    
    navigator.getUserMedia = (
      navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia
    );

    // audio
    var rec;
    var context;

    function startRecord() {
      navigator.getUserMedia({audio: true}, function(localMediaStream){
    	context = new Context();
        var mediaStreamSource = context.createMediaStreamSource(localMediaStream);
        rec = new Recorder(mediaStreamSource);
        rec.record();
      }, function(err){
        console.log('Not supported');
      });
    }

    function stopRecord() {
      rec.stop();
      context.close();

      rec.exportWAV(function(e){
        getBase64(e, function(base64){
        	rec.clear();
        	send("<audio preload controls src='"+base64+"'/>");
        })
      });
    }
    
 	// video
    var video;
 	var recorder;

    function startVideo() {
      navigator.getUserMedia({video: true, audio: true}, function(localMediaStream){
        recorder = new MediaRecorder(localMediaStream);
        recorder.ondataavailable = function(evt) {
            videoBlob = new Blob([evt.data], { type: evt.data.type });
            console.log(videoBlob)
            getBase64(videoBlob, function(base64){
            	send("<video width='300' height='300' controls src='"+base64+"'/>");
            })
        }
        recorder.start();
        
        context = new Context();
        var mediaStreamSource = context.createMediaStreamSource(localMediaStream);
        video = document.querySelector('video');
        video.src = URL.createObjectURL(localMediaStream);
        video.play();
      }, function(err){
        console.log('Not supported');
      });
    }

    function stopVideo() {
    	video.pause();
    	recorder.stop();
    	context.close();
    }

    var socketChat = socket, socketService = null;
    function switchChatService(){
    	if(wsurl.endsWith('/chat')){
    		wsurl = wsurl.replace('/chat', '/service')
    		if(!socketService) {
    			socketService = new ReconnectingWebSocket(wsurl);
    			socketService.onmessage = socket.onmessage;
    		}
    		socket = socketService;
    	}else{
    		socket = socketChat;
    	}
    }
</script>
<style type="text/css">
    html,body {width:100%;height:100%;}
    html,body,ul,ol,dl,li,dt,dd,p,blockquote,fieldset,legend,img,form,h1,h2,h3,h4,h5,h6 {margin:0;padding:0;}
    body {
        font:normal 14px/1.5 Arial,Helvetica,'Bitstream Vera Sans',sans-serif;
        background: #c5deea; /* Old browsers */
        background: -moz-linear-gradient(top, #c5deea 0%, #066dab 100%); /* FF3.6+ */
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #c5deea), color-stop(100%, #066dab)); /* Chrome,Safari4+ */
        background: -webkit-linear-gradient(top, #c5deea 0%, #066dab 100%); /* Chrome10+,Safari5.1+ */
        background: -o-linear-gradient(top, #c5deea 0%, #066dab 100%); /* Opera 11.10+ */
        background: -ms-linear-gradient(top, #c5deea 0%, #066dab 100%); /* IE10+ */
        background: linear-gradient(to bottom, #c5deea 0%, #066dab 100%); /* W3C */
        height: 90%;
    }

    .center {
        margin-left: auto;
        margin-right: auto;
        width: 70%;
        background: white;
    }

    .chatform {
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 0;
        width: 100%;
        height: 36px;
    }
    form{
        width: 100%;
    }
    label{
        display: inline;
        width: 20px;
    }
    #msg{
        display: inline;
        width: 80%;
        height: 90%
    }

</style>
</head>
<body>
<div class="page">
    <div class="center" onpaste="onPaste()">
        <h1>Web Socket Chat</h1>
        <div id="chat" style="height:100%;width: 100%; overflow: scroll;">

        </div>

        <form onsubmit="return false;" class="chatform" action="">
            <label for="msg" style="display:inline" ondblclick="switchChatService()">Message</label>
            <input type="text" name="message" id="msg"  onkeypress="if(event.keyCode==13) { send(this.form.message.value); this.value='' } " placeholder="支持粘贴QQ截图"/>
            <label title="选择图片"><input type="file" style="display:none" onchange="onSelect()" accept="image/*">➕</label>
            <label title="按住录音，松开发送" onmousedown="startRecord()" onmouseup="stopRecord()">录音</label>
            <label title="按住录像，松开发送" onmousedown="startVideo()" onmouseup="stopVideo()" onmousein="">视频</label>
        </form>
        <video width="300" height="300" style="border:solid;position:absolute;bottom:5%;right:15%"></video>
    </div>
</div>
</body>
</html>